package io.gitee.zhangbinhub.acp.cloud.admin.conf;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * @since JDK 17
 */
@Configuration
public class AdminServerAutoConfiguration {

    private final String adminContextPath;

    @Autowired
    public AdminServerAutoConfiguration(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    /**
     * http 验证策略配置
     *
     * @param http http 安全验证对象
     * @throws Exception 异常
     */
    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");
        return http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(authorize ->
                        authorize.requestMatchers(new AntPathRequestMatcher(adminContextPath + "/assets/**"),
                                        new AntPathRequestMatcher(adminContextPath + "/instances"),
                                        new AntPathRequestMatcher(adminContextPath + "/instances/**"),
                                        new AntPathRequestMatcher(adminContextPath + "/login"),
                                        new AntPathRequestMatcher(adminContextPath + "/error"),
                                        new AntPathRequestMatcher(adminContextPath + "/webjars/**"),
                                        new AntPathRequestMatcher(adminContextPath + "/notifications/**"),
                                        new AntPathRequestMatcher(adminContextPath + "/proxy.stream"))
                                .permitAll().anyRequest().authenticated()).httpBasic(Customizer.withDefaults())
                .formLogin(configure -> configure.loginPage(adminContextPath + "/login").successHandler(successHandler))
                .logout(configure -> configure.logoutUrl(adminContextPath + "/logout")).build();
    }

}
